// Markdown预览类
class MarkdownPreview {
    constructor(element) {
        this.element = element;
        this.lastContent = '';
        this.renderTimeout = null;
        this.mermaidInitialized = false;
        
        this.init();
    }

    init() {
        // 初始化Mermaid
        if (typeof mermaid !== 'undefined') {
            mermaid.initialize({
                startOnLoad: false,
                theme: 'default',
                securityLevel: 'loose',
                fontFamily: 'Arial, sans-serif'
            });
            this.mermaidInitialized = true;
        }

        // 初始化marked
        if (typeof marked !== 'undefined') {
            marked.setOptions({
                highlight: function(code, lang) {
                    // 这里可以集成代码高亮库
                    return code;
                },
                breaks: true,
                gfm: true
            });
        }
    }

    // 更新预览内容
    update(content) {
        if (content === this.lastContent) {
            return;
        }
        
        this.lastContent = content;
        
        // 防抖处理
        if (this.renderTimeout) {
            clearTimeout(this.renderTimeout);
        }
        
        this.renderTimeout = setTimeout(() => {
            this.render(content);
        }, 300);
    }

    // 渲染内容
    async render(content) {
        if (!content.trim()) {
            this.element.innerHTML = this.getWelcomeMessage();
            return;
        }

        try {
            // 预处理内容
            let processedContent = this.preprocessContent(content);
            
            // 使用marked渲染Markdown
            let html = '';
            if (typeof marked !== 'undefined') {
                html = marked.parse(processedContent);
            } else {
                // 降级处理
                html = this.simpleMarkdownRender(processedContent);
            }
            
            // 后处理HTML
            html = await this.postprocessHTML(html);
            
            this.element.innerHTML = html;
            
            // 渲染特殊内容
            await this.renderSpecialContent();
            
        } catch (error) {
            console.error('预览渲染错误:', error);
            this.element.innerHTML = `<div class="error">预览渲染失败: ${error.message}</div>`;
        }
    }

    // 预处理内容
    preprocessContent(content) {
        // 处理任务列表
        content = content.replace(/^(\s*)-\s+\[([ x])\]\s+(.+)$/gm, (match, indent, checked, text) => {
            const isChecked = checked === 'x';
            return `${indent}- <input type="checkbox" ${isChecked ? 'checked' : ''} disabled> ${text}`;
        });

        // 处理表格对齐
        content = content.replace(/\|(\s*):?-+:?\s*\|/g, (match) => {
            return match; // 保持原样，让marked处理
        });

        return content;
    }

    // 后处理HTML
    async postprocessHTML(html) {
        // 处理代码块
        html = html.replace(/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g, (match, lang, code) => {
            return `<pre><code class="language-${lang}">${this.escapeHtml(code)}</code></pre>`;
        });

        // 处理链接（添加target="_blank"）
        html = html.replace(/<a href="([^"]*)">/g, '<a href="$1" target="_blank" rel="noopener noreferrer">');

        // 处理图片（添加懒加载）
        html = html.replace(/<img src="([^"]*)" alt="([^"]*)">/g, '<img src="$1" alt="$2" loading="lazy">');

        return html;
    }

    // 渲染特殊内容
    async renderSpecialContent() {
        // 渲染Mermaid图表
        await this.renderMermaidCharts();
        
        // 渲染LaTeX公式
        this.renderMathFormulas();
        
        // 渲染PlantUML图表
        await this.renderPlantUMLCharts();
    }

    // 渲染Mermaid图表
    async renderMermaidCharts() {
        if (!this.mermaidInitialized) return;

        // 查找所有Mermaid代码块
        const mermaidBlocks = this.element.querySelectorAll('code.language-mermaid, .mermaid');
        
        for (let i = 0; i < mermaidBlocks.length; i++) {
            const block = mermaidBlocks[i];
            const code = block.textContent.trim();
            
            if (!code) continue;
            
            const id = `mermaid-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
            
            try {
                // 验证Mermaid语法
                const isValid = await this.validateMermaidSyntax(code);
                if (!isValid) {
                    throw new Error('无效的Mermaid语法');
                }
                
                const { svg } = await mermaid.render(id, code);
                const wrapper = document.createElement('div');
                wrapper.className = 'mermaid-wrapper';
                wrapper.setAttribute('data-mermaid-type', this.detectMermaidType(code));
                wrapper.innerHTML = svg;
                
                // 添加工具栏
                const toolbar = this.createMermaidToolbar(code, svg);
                wrapper.appendChild(toolbar);
                
                block.parentNode.replaceWith(wrapper);
            } catch (error) {
                console.error('Mermaid渲染错误:', error);
                const errorDiv = document.createElement('div');
                errorDiv.className = 'mermaid-error';
                errorDiv.innerHTML = `
                    <div class="error-header">
                        <span class="error-icon">⚠️</span>
                        <span class="error-title">Mermaid图表渲染失败</span>
                    </div>
                    <div class="error-message">${this.escapeHtml(error.message)}</div>
                    <details class="error-details">
                        <summary>查看原始代码</summary>
                        <pre><code>${this.escapeHtml(code)}</code></pre>
                    </details>
                `;
                block.parentNode.replaceWith(errorDiv);
            }
        }
    }

    // 验证Mermaid语法
    async validateMermaidSyntax(code) {
        try {
            // 基本语法检查
            const lines = code.split('\n').filter(line => line.trim());
            if (lines.length === 0) return false;
            
            // 检查是否有有效的图表类型
            const validTypes = ['graph', 'flowchart', 'sequenceDiagram', 'classDiagram', 'stateDiagram', 'erDiagram', 'journey', 'gantt', 'pie', 'gitgraph'];
            const firstLine = lines[0].trim().toLowerCase();
            
            return validTypes.some(type => firstLine.startsWith(type.toLowerCase()));
        } catch (error) {
            return false;
        }
    }

    // 检测Mermaid图表类型
    detectMermaidType(code) {
        const firstLine = code.split('\n')[0].trim().toLowerCase();
        
        if (firstLine.startsWith('graph')) return 'graph';
        if (firstLine.startsWith('flowchart')) return 'flowchart';
        if (firstLine.startsWith('sequencediagram')) return 'sequence';
        if (firstLine.startsWith('classdiagram')) return 'class';
        if (firstLine.startsWith('statediagram')) return 'state';
        if (firstLine.startsWith('erdiagram')) return 'er';
        if (firstLine.startsWith('journey')) return 'journey';
        if (firstLine.startsWith('gantt')) return 'gantt';
        if (firstLine.startsWith('pie')) return 'pie';
        if (firstLine.startsWith('gitgraph')) return 'gitgraph';
        
        return 'unknown';
    }

    // 创建Mermaid工具栏
    createMermaidToolbar(code, svg) {
        const toolbar = document.createElement('div');
        toolbar.className = 'mermaid-toolbar';
        
        // 下载SVG按钮
        const downloadBtn = document.createElement('button');
        downloadBtn.className = 'mermaid-tool-btn';
        downloadBtn.innerHTML = '📥 下载SVG';
        downloadBtn.title = '下载SVG图片';
        downloadBtn.onclick = () => this.downloadMermaidSVG(svg, 'mermaid-chart.svg');
        
        // 复制代码按钮
        const copyBtn = document.createElement('button');
        copyBtn.className = 'mermaid-tool-btn';
        copyBtn.innerHTML = '📋 复制代码';
        copyBtn.title = '复制Mermaid代码';
        copyBtn.onclick = () => this.copyMermaidCode(code);
        
        // 全屏查看按钮
        const fullscreenBtn = document.createElement('button');
        fullscreenBtn.className = 'mermaid-tool-btn';
        fullscreenBtn.innerHTML = '🔍 全屏';
        fullscreenBtn.title = '全屏查看';
        fullscreenBtn.onclick = () => this.showMermaidFullscreen(svg);
        
        toolbar.appendChild(downloadBtn);
        toolbar.appendChild(copyBtn);
        toolbar.appendChild(fullscreenBtn);
        
        return toolbar;
    }

    // 下载Mermaid SVG
    downloadMermaidSVG(svg, filename) {
        const blob = new Blob([svg], { type: 'image/svg+xml' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        URL.revokeObjectURL(url);
    }

    // 复制Mermaid代码
    async copyMermaidCode(code) {
        try {
            await navigator.clipboard.writeText(code);
            // 显示复制成功提示
            this.showToast('代码已复制到剪贴板');
        } catch (error) {
            console.error('复制失败:', error);
            this.showToast('复制失败', 'error');
        }
    }

    // 全屏显示Mermaid图表
    showMermaidFullscreen(svg) {
        const modal = document.createElement('div');
        modal.className = 'mermaid-modal';
        modal.innerHTML = `
            <div class="modal-backdrop" onclick="this.parentElement.remove()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>Mermaid图表</h3>
                    <button class="modal-close" onclick="this.closest('.mermaid-modal').remove()">×</button>
                </div>
                <div class="modal-body">
                    ${svg}
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    // 显示提示消息
    showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);
        
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }

    // 渲染LaTeX公式
    renderMathFormulas() {
        if (typeof katex === 'undefined') return;

        // 先处理块级公式 $$...$$ (必须在行内公式之前处理)
        this.element.innerHTML = this.element.innerHTML.replace(/\$\$([^$]*(?:\$(?!\$)[^$]*)*)\$\$/g, (match, formula) => {
            try {
                const cleanFormula = formula.trim();
                if (!cleanFormula) return match;
                
                return `<div class="katex-display">${katex.renderToString(cleanFormula, { 
                    displayMode: true,
                    throwOnError: false,
                    errorColor: '#cc0000',
                    macros: {
                        "\\RR": "\\mathbb{R}",
                        "\\NN": "\\mathbb{N}",
                        "\\ZZ": "\\mathbb{Z}",
                        "\\QQ": "\\mathbb{Q}",
                        "\\CC": "\\mathbb{C}"
                    }
                })}</div>`;
            } catch (error) {
                console.error('KaTeX块级公式渲染错误:', error);
                return `<div class="katex-error">数学公式错误: ${formula}</div>`;
            }
        });

        // 再处理行内公式 $...$
        this.element.innerHTML = this.element.innerHTML.replace(/(?<!\$)\$([^$\n]+)\$(?!\$)/g, (match, formula) => {
            try {
                const cleanFormula = formula.trim();
                if (!cleanFormula) return match;
                
                return katex.renderToString(cleanFormula, { 
                    displayMode: false,
                    throwOnError: false,
                    errorColor: '#cc0000',
                    macros: {
                        "\\RR": "\\mathbb{R}",
                        "\\NN": "\\mathbb{N}",
                        "\\ZZ": "\\mathbb{Z}",
                        "\\QQ": "\\mathbb{Q}",
                        "\\CC": "\\mathbb{C}"
                    }
                });
            } catch (error) {
                console.error('KaTeX行内公式渲染错误:', error);
                return `<span class="katex-error">公式错误: ${formula}</span>`;
            }
        });
    }

    // 渲染PlantUML图表
    async renderPlantUMLCharts() {
        const plantumlBlocks = this.element.querySelectorAll('code.language-plantuml, code.language-puml');
        
        // 获取应用设置
        const app = window.markEditApp;
        const settings = app ? app.settings : {};
        
        // 检查是否启用PlantUML
        if (settings.enablePlantuml === false) {
            return;
        }
        
        // 检查离线模式
        if (settings.plantumlOfflineMode === true) {
            this.showPlantUMLOfflineNotice(plantumlBlocks);
            return;
        }
        
        for (const block of plantumlBlocks) {
            const code = block.textContent;
            
            try {
                const response = await fetch('/api/render/chart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        type: 'plantuml',
                        content: code,
                        settings: {
                            format: 'svg',
                            dpi: 300,
                            server: settings.plantumlServer || 'http://localhost:8081'
                        }
                    })
                });

                const result = await response.json();
                if (result.success && result.data && result.data.image_data) {
                    const wrapper = document.createElement('div');
                    wrapper.className = 'plantuml-wrapper';
                    wrapper.innerHTML = `<img src="data:image/svg+xml;base64,${result.data.image_data}" alt="PlantUML图表">`;
                    block.parentNode.replaceWith(wrapper);
                } else {
                    throw new Error(result.message || 'PlantUML渲染失败');
                }
            } catch (error) {
                console.error('PlantUML渲染错误:', error);
                
                // 在离线环境中提供更友好的fallback
                const fallbackDiv = document.createElement('div');
                fallbackDiv.className = 'plantuml-fallback';
                fallbackDiv.innerHTML = `
                    <div class="offline-notice">
                        <h4>📊 PlantUML 图表</h4>
                        <p>PlantUML服务不可用 (${settings.plantumlServer || 'http://localhost:8081'})</p>
                        <details>
                            <summary>查看PlantUML代码</summary>
                            <pre><code>${this.escapeHtml(code)}</code></pre>
                        </details>
                        <small>提示：检查PlantUML服务器配置或启用离线模式</small>
                    </div>
                `;
                block.parentNode.replaceWith(fallbackDiv);
            }
        }
    }
    
    // 显示PlantUML离线模式通知
    showPlantUMLOfflineNotice(plantumlBlocks) {
        for (const block of plantumlBlocks) {
            const code = block.textContent;
            const fallbackDiv = document.createElement('div');
            fallbackDiv.className = 'plantuml-fallback offline-mode';
            fallbackDiv.innerHTML = `
                <div class="offline-notice">
                    <h4>📊 PlantUML 图表 (离线模式)</h4>
                    <p>当前处于离线模式，PlantUML图表渲染已禁用</p>
                    <details>
                        <summary>查看PlantUML代码</summary>
                        <pre><code>${this.escapeHtml(code)}</code></pre>
                    </details>
                    <small>提示：在设置中关闭离线模式以启用图表渲染</small>
                </div>
            `;
            block.parentNode.replaceWith(fallbackDiv);
        }
    }

    // 简单Markdown渲染（降级方案）
    simpleMarkdownRender(content) {
        let html = content;
        
        // 标题
        html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
        html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
        html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
        
        // 粗体和斜体
        html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
        
        // 链接
        html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
        
        // 图片
        html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">');
        
        // 代码
        html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
        
        // 段落
        html = html.replace(/\n\n/g, '</p><p>');
        html = '<p>' + html + '</p>';
        
        // 换行
        html = html.replace(/\n/g, '<br>');
        
        return html;
    }

    // 获取欢迎消息
    getWelcomeMessage() {
        return `
            <div class="welcome-message">
                <h2>欢迎使用 MarkEdit</h2>
                <p>开始在左侧编辑器中输入Markdown内容，右侧将实时显示预览效果。</p>
                <h3>支持的功能：</h3>
                <ul>
                    <li>✅ 标准Markdown语法</li>
                    <li>✅ PlantUML图表</li>
                    <li>✅ Mermaid图表</li>
                    <li>✅ LaTeX数学公式</li>
                    <li>✅ 代码高亮</li>
                    <li>✅ 表格支持</li>
                    <li>✅ 任务列表</li>
                </ul>
                <h3>快捷键：</h3>
                <ul>
                    <li><kbd>Ctrl+B</kbd> - 粗体</li>
                    <li><kbd>Ctrl+I</kbd> - 斜体</li>
                    <li><kbd>Ctrl+K</kbd> - 链接</li>
                    <li><kbd>Ctrl+M</kbd> - 行内数学公式</li>
                    <li><kbd>Ctrl+Shift+M</kbd> - 块级数学公式</li>
                    <li><kbd>Ctrl+S</kbd> - 保存</li>
                    <li><kbd>Ctrl+N</kbd> - 新建</li>
                    <li><kbd>Ctrl+O</kbd> - 打开</li>
                </ul>
                <h3>数学公式示例：</h3>
                <ul>
                    <li>行内公式：<code>$E = mc^2$</code></li>
                    <li>块级公式：<code>$$\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}$$</code></li>
                    <li>分数：<code>$\\frac{a}{b}$</code></li>
                    <li>根号：<code>$\\sqrt{x^2 + y^2}$</code></li>
                    <li>求和：<code>$\\sum_{i=1}^{n} x_i$</code></li>
                </ul>
            </div>
        `;
    }

    // HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 清空预览
    clear() {
        this.element.innerHTML = this.getWelcomeMessage();
        this.lastContent = '';
    }

    // 滚动到顶部
    scrollToTop() {
        this.element.scrollTop = 0;
    }

    // 滚动到底部
    scrollToBottom() {
        this.element.scrollTop = this.element.scrollHeight;
    }
}